package com.omuao.message.websocket.manager.impl;

import com.omuao.message.websocket.config.RocksDbConfig;
import com.omuao.message.websocket.facade.ClientSessionManager;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

/**
 * Rocks DB 会话管理器
 *
 * @author omuao
 */
@Repository
public class RocksDbClientSessionManagerImpl implements ClientSessionManager {

    @Autowired
    @Qualifier(RocksDbConfig.ROCK_DB_SESSION)
    RocksDB rocksDB;

    @Override
    public void put(String clientId) {
        try {
            rocksDB.put(clientId.getBytes(), new byte[]{1});
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void remove(String clientId) {
        byte[] data = null;
        try {
            data = rocksDB.get(clientId.getBytes());
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
        if (data == null) {
            return;
        }
        try {
            rocksDB.delete(clientId.getBytes());
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean contains(String clientId) {

        try {
            boolean flag = rocksDB.get(clientId.getBytes()) != null;
            return flag;
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
        return false;
    }
}
